package cn.com.blueInfo.bpm.template.repository.impl;

import cn.com.blueInfo.bpm.common.entity.BaseEntity;
import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.repository.BaseRepository;
import cn.com.blueInfo.bpm.template.entity.Instance;
import cn.com.blueInfo.bpm.template.enums.InstanceProcessStatus;
import cn.com.blueInfo.bpm.template.mapper.InstanceMapper;
import cn.com.blueInfo.bpm.template.repository.InstanceRepository;
import cn.com.blueInfo.bpm.template.request.InstanceDTO;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 流程运行时实例表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:30:44
 */
@Log4j2
@Service
public class InstanceRepositoryImpl
        extends ServiceImpl<InstanceMapper, Instance>
        implements InstanceRepository, BaseRepository<Instance, InstanceDTO.QueryDTO> {

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    /**
     * 提供获取 CurrentLoginUserInfo 的方法（由实现类提供，避免接口中注入）
     * @return CurrentLoginUserInfo
     */
    @Override
    public CurrentLoginUserInfo getCurrentLoginUserInfo() {
        return currentLoginUserInfo;
    }

    /**
     * 新增流程运行时实例
     * @param instance 流程运行时实例参数
     */
    @Override
    public Integer createInstance(Instance instance) {
        return sqlExecuteResult(save(instance));
    }

    /**
     * 批量新增流程运行时实例
     * @param instanceList 流程运行时实例参数列表
     */
    @Override
    public Integer batchCreateInstance(List<Instance> instanceList) {
        return sqlExecuteResult(saveBatch(instanceList), instanceList.size());
    }

    /**
     * 删除流程运行时实例
     * @param instanceId 流程运行时实例ID
     */
    @Override
    public Integer deleteInstance(Long instanceId) {
        Instance instance = new Instance();
        instance.setId(instanceId);
        instance.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(instance));
    }

    /**
     * 批量删除流程运行时实例
     * @param instanceIdList 流程运行时实例ID列表
     */
    @Override
    public Integer batchDeleteInstance(List<Long> instanceIdList) {
        List<Instance> instanceList = new ArrayList<>();
        for (Long instanceId : instanceIdList) {
            Instance instance = new Instance();
            instance.setId(instanceId);
            instance.setDeleted(BaseDeleted.DELETED);
            instanceList.add(instance);
        }
        return sqlExecuteResult(removeBatchByIds(instanceList), instanceList.size());
    }

    /**
     * 更新部分流程运行时实例
     * @param instance 流程运行时实例参数
     */
    @Override
    public Integer updateInstancePartial(Instance instance) {
        validateUpdateId(instance.getId());
        LambdaUpdateWrapper<Instance> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Instance::getId, instance.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部流程运行时实例
     * @param instance 流程运行时实例参数
     */
    @Override
    public Integer updateInstance(Instance instance) {
        validateUpdateId(instance.getId());
        return sqlExecuteResult(updateById(instance));
    }

    /**
     * 查询一条流程运行时实例
     * @param instanceId 流程运行时实例ID
     */
    @Override
    public Instance getInstanceById(Long instanceId) {
        LambdaQueryWrapper<Instance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Instance::getId, instanceId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询流程运行时实例
     * @param instanceQueryDTO 流程运行时实例参数
     */
    @Override
    public Page<Instance> getInstancePage(InstanceDTO.QueryDTO instanceQueryDTO) {
        Page<Instance> instancePage = new Page<>(
                instanceQueryDTO.getPage(), instanceQueryDTO.getSize());
        LambdaQueryWrapper<Instance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, instanceQueryDTO);

        BaseDeleted deleted = instanceQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(instancePage, queryWrapper);
        } else {
            return page(instancePage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 流程运行时实例 数量
     * @param instanceQueryDTO 流程运行时实例参数
     */
    @Override
    public Long getInstanceCount(InstanceDTO.QueryDTO instanceQueryDTO) {
        LambdaQueryWrapper<Instance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, instanceQueryDTO);

        BaseDeleted deleted = instanceQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 流程运行时实例
     * @param instanceQueryDTO 流程运行时实例参数
     */
    @Override
    public List<Instance> getInstanceList(InstanceDTO.QueryDTO instanceQueryDTO) {
        LambdaQueryWrapper<Instance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, instanceQueryDTO);

        BaseDeleted deleted = instanceQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<Instance> queryWrapper, InstanceDTO.QueryDTO instanceQueryDTO) {

        Long processId = instanceQueryDTO.getProcessId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(processId), Instance::getProcessId, processId);

        String processCode = instanceQueryDTO.getProcessCode();
        queryWrapper.eq(StringUtils.isNotBlank(processCode), Instance::getProcessCode, processCode);

        String subject = instanceQueryDTO.getSubject();
        queryWrapper.eq(StringUtils.isNotBlank(subject), Instance::getSubject, subject);

        Long applicantId = instanceQueryDTO.getApplicantId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(applicantId), Instance::getApplicantId, applicantId);

        String applicantName = instanceQueryDTO.getApplicantName();
        queryWrapper.eq(StringUtils.isNotBlank(applicantName), Instance::getApplicantName, applicantName);

        Long deptId = instanceQueryDTO.getDeptId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(deptId), Instance::getDeptId, deptId);

        String deptName = instanceQueryDTO.getDeptName();
        queryWrapper.eq(StringUtils.isNotBlank(deptName), Instance::getDeptName, deptName);

        LocalDateTime applyTime = instanceQueryDTO.getApplyTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(applyTime), Instance::getApplyTime, applyTime);

        Integer currentNodeId = instanceQueryDTO.getCurrentNodeId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(currentNodeId), Instance::getCurrentNodeId, currentNodeId);

        InstanceProcessStatus processStatus = instanceQueryDTO.getProcessStatus();
        queryWrapper.eq(ObjectUtils.isNotEmpty(processStatus), Instance::getProcessStatus, processStatus);

        LocalDateTime cancelTime = instanceQueryDTO.getCancelTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(cancelTime), Instance::getCancelTime, cancelTime);

        LocalDateTime completeTime = instanceQueryDTO.getCompleteTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(completeTime), Instance::getCompleteTime, completeTime);

        addQueryWrapper(queryWrapper, instanceQueryDTO, getCommonColumn());

    }

    private Map<String, SFunction<Instance, ?>> getCommonColumn() {
        return BaseEntity.getCommonColumn(
                Instance::getOrderNumber,
                Instance::getTenantId,
                Instance::getApplicationId,
                Instance::getStatus,
                Instance::getDeleted,
                Instance::getDeleteUserId,
                Instance::getDeleteTime,
                Instance::getRemark,
                Instance::getCreateUserId,
                Instance::getCreateTime,
                Instance::getUpdateUserId,
                Instance::getUpdateTime,
                Instance::getExtend1,
                Instance::getExtend2,
                Instance::getExtend3);
    }

}
